package com.prs.crm.dao.stock.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.stock.ProductDao;
import com.prs.crm.domain.stock.Product;

public class ProductDaoImpl extends BaseDaoImpl<Product> implements ProductDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<Product> getBatchNum() {
		return (List<Product> )getHibernateTemplate().execute(   
			      new HibernateCallback() {   
			        public Object doInHibernate(Session session) throws HibernateException {   
			        	Criteria criteria =  session.createCriteria(Product.class);
                 List<Product>  alits=criteria.list();
                 List<Product>  blist=criteria.list();
                 for(int i=0;i<alits.size();i++){
                	 Product product=alits.get(i);	
                	 String BatchNum=product.getBatchNum();              	 
                	 int judge=0;
                		 for(int j=0;j<blist.size();j++){
                			 Product product1=blist.get(j);	
                			 if(BatchNum.equals(product1.getBatchNum())){
                        		 judge++;
                        	 }
                			 if(judge>1){
                				 blist.remove(j); 
                			 }
                		 }
                	
                	 
                	 
                	 
                 }
			        	return  blist;
			        }   
			      }   
			    );  
	}
	@SuppressWarnings("unchecked")
	@Override
	public Product getProductBycode(final String productcode) {
		// TODO Auto-generated method stub
		return (Product)this.getHibernateTemplate().execute(
			      new HibernateCallback() {   
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Product.class);
				        	criteria.add(Restrictions.eq("productcode", productcode));		        	
				        	List<Product> result = criteria.list();
				        	if(result.size()==0){
				        		return null;
				        	}else{
				        		return result.get(0);
				        	}
				        }   
				 } );
	}
	@Override
	public void saveOrProduct(Product product) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().saveOrUpdate(product);
	}

	

}
